using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class SimpleMove : MonoBehaviour
{
    private CharacterController controller;
    private Animator animator;
    private Vector3 playerVelocity;
    private bool groundedPlayer;
    private float playerSpeed = 2.0f;
    private float jumpHeight = 1.0f;
    private float gravityValue = -9.81f;
    private bool inputJump = false;

    private Vector2 moveInput;

    [SerializeField]private float targetSpeed;

    private void Start()
    {
        controller = gameObject.GetComponent<CharacterController>();
        animator = gameObject.GetComponentInChildren<Animator>();
    }

    void Update()
    {
        groundedPlayer = controller.isGrounded;
        if (groundedPlayer && playerVelocity.y < 0)
        {
            playerVelocity.y = 0f;
            animator.SetBool("Jump", false);
        }

        Vector3 move = new Vector3(moveInput.x, 0, moveInput.y);
        controller.Move(move * Time.deltaTime * playerSpeed);
        //animator.SetFloat("Speed", moveInput.y);
        animator.SetFloat("Speed",moveInput.magnitude*targetSpeed,0.1f,Time.deltaTime);
        //animator.SetFloat("Direction",moveInput.x);

        if (move != Vector3.zero)
        {
            gameObject.transform.forward = move;
        }
        

        // Changes the height position of the player..
        if (inputJump && groundedPlayer)
        {
            animator.SetBool("Jump",true);
            inputJump = false;
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
        }

        playerVelocity.y += gravityValue * Time.deltaTime;
        controller.Move(playerVelocity * Time.deltaTime);
    }

    public void MoveInput(InputAction.CallbackContext callbackContext) 
    {
        moveInput = callbackContext.ReadValue<Vector2>();
    }
    public void JumpInput(InputAction.CallbackContext ctx) 
    {
        inputJump=ctx.ReadValueAsButton();
    }
}
